import React from 'react'
import { fetchPost, formFetchPost,origin } from './common/request'
import { Table, Upload, Spin, Card, Button, Radio, Form, Message, Row, Col, DatePicker, Modal, Input, Lable, Select, Popconfirm, Icon } from 'antd'
import { successNotify, errorNotify } from './common/common'

const FormItem = Form.Item
const RadioGroup = Radio.Group

const {TextArea} = Input
const {Option} = Select

class SendOperationMsg extends React.Component {
  constructor (props) {
    super(props)
  }

  state = {
    appList: [],
    templateList: [],
    record: {},
    getTemplateParams:{},

    appId : null,
    msgType : '4',
    isBatchEntering: false,
    //文件传输
    fileList: [],

    templateLoading: false,
    sendLoading: false,

  }

  resetForm = () => {
    this.setState({
      appId : null,
      msgType : '4',
      record: {},
      templateList: [],
      isBatchEntering: false,
      fileList: [],
    })
    this.props.form.resetFields()
  }

  componentWillMount = () => {
    this.state.isBatchEntering = false
    this.getAppList()
  }

  handleUpload (info) {
    if (info) {
      let fileList = info.fileList
      fileList = fileList.slice(-1)
      this.setState({fileList,})
    }
  }

  enteringModeChange = () => {
    this.setState({
      isBatchEntering: !this.state.isBatchEntering
    })
  }

  userIdListChange = (e) => {
    console.log(e)
    this.state.userIdList = e.target.value
    console.log(this.state.record)
  }

  templateChange = (value, option) => {
    this.state.record.businessRefId = value

    for (let a of this.state.templateList) {
      if (this.state.record.businessRefId === a.businessRefId) {
        this.state.record.bizFunctionDesc = a.bizFunctionDesc
        this.state.record.channelName = a.channelName
        this.state.record.messageTemplateDesc = a.messageTemplateDesc
        this.state.record.sendRuleName = a.sendRuleName
        this.state.record.serviceName = a.serviceName
        return
      }
    }
  }

  getAppList () {
    fetchPost('/appInfo/getAppInfo').then(json => {
      if (json.data != null) {
        this.setState({
          appList: json.data
        })
      } else{
        errorNotify(json.msg)
      }
    })
  }

  getTemplateList = () => {
    if (!this.state.appId || !this.state.msgType)
      return
    this.setState({
      templateLoading: true,
    })
    let param = {}
    param.appId = this.state.appId
    param.msgType = this.state.msgType
    fetchPost('/business/getSmsMsgTemplateInfoByAppId', param).then(json => {
      if (json.data != null) {
        this.setState({
          templateList: json.data,
          templateLoading: false,
        })
      } else{
        errorNotify(json.msg)
        this.setState({
          templateLoading: false,
        })
      }
    })
  }

  msgTypeChange = (value) =>{

    this.state.msgType = value;
    this.props.form.resetFields(['template'])
    this.getTemplateList()
  }

  appChange = (value) => {
    // 将除了userIdList的其他清除
    this.state.appId = value
    this.props.form.resetFields(['template'])
    this.getTemplateList()
  }

  templateDownload = () => {
    fetchPost('/sendMsg/getExcelTemplate').then(json => {
      if (json.code != 200) {
        errorNotify('Failed to get Excel template', json.msg)
      }
      if (json.data != null) {
        window.open(json.data)
      }

    })
  }

  submit = () => {
    console.log(this.state.record)
    this.props.form.validateFields((err, values) => {
      if (!err) {
        // 判断是新增还是修改
        let param = {}
        param.businessRefId = this.state.record.businessRefId
        param.appId = this.state.appId
        if (this.state.isBatchEntering) {
          param.fileOssUrl = this.state.fileList[0].response.data
        } else {
          param.textList = this.state.userIdList
        }

        console.log(this.state.record)
        console.log(param)

        this.setState({
          sendLoading : true,
        })
        fetchPost('/sendMsg/doBatchSendMsgByHand', param).then(json => {
          this.setState({
            sendLoading : false,
          })
          if (json.code != 200) {
            errorNotify('Exception', json.msg)
          }
          else {
            this.resetForm()
            successNotify('Sent successfully')
          }
        })
      }
    })
  }

  render () {
    const appOptions = this.state.appList.map(d => <Option value={d.appId}>{d.appName}</Option>)
    const templateOptions = this.state.templateList.map(d => <Option
      value={d.businessRefId}>{d.bizFunctionDesc}:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{d.messageTemplateDesc}</Option>)
    const {getFieldDecorator} = this.props.form
    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 2},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 10},
      },
    }
    const formItemLayout2 = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 8},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16},
      },
    }
    return (

      <Card>
        <Spin spinning={this.state.sendLoading} delay={500}>
          <Form>

            <FormItem {...formItemLayout} label="SMS type" >
              {getFieldDecorator('msgType', {
                initialValue : this.state.msgType,
                rules: [
                  {required: true, message: 'SMS type cannot be empty!'},
                ],
              })(
              <Select placeholder="Please select a text message type!" onSelect={this.msgTypeChange}>
                <Option value="3">Notification class SMS</Option>
                <Option value="4">Marketing SMS</Option>
              </Select>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="Send the object">
              {getFieldDecorator('sendObject', {
                initialValue: this.state.isBatchEntering,
                rules: [
                  {required: true, message: 'Send object cannot be empty!'},
                ],
              })(
                <RadioGroup onChange={this.enteringModeChange}>
                  <Radio value={false}>Manual input</Radio>
                  <Radio value={true}>Batch entry</Radio>
                  <a onClick={this.templateDownload} download="Message template">
                    Template download
                  </a>
                </RadioGroup>
              )}

            </FormItem>
            <Row>
              <Col span={24} push={2}>
                <Col span={10}>
                  {
                    this.state.isBatchEntering ?
                      <FormItem>
                        <Upload onChange={this.handleUpload.bind(this)} defaultFileList={this.state.fileList}
                                name="file" fileList={this.state.fileList}
                                action={origin + '/sendMsg/uploadExcelInfo'}>
                          <Button type="ghost">
                            <Icon type="upload"/> Click to upload
                          </Button>
                        </Upload>
                      </FormItem>
                      :
                      <FormItem>
                        {getFieldDecorator ('userIdList', {
                          rules: [
                            {required: true, message: 'Please choose to upload the file or fill in the sender'},],
                        })(
                          <TextArea autosize={{minRows: 4, maxRows: 10}} size={20} onChange={this.userIdListChange}
                                    placeholder='Multiple usernames or phone numbers are separated by commas. For example: "122,123,234"' />
                        )}
                      </FormItem>
                  }
                </Col>
              </Col>
            </Row>


            <Row gutter={1}>
              <Col span={6}>
                <FormItem {...formItemLayout2} label="Message template">
                  {getFieldDecorator('appId', {
                    initialValue: this.state.record ? this.state.record.appId || null : null,
                    rules: [
                      {required: true, message: 'Please select the app name!'},
                    ],
                  })(
                    <Select placeholder="Please" onSelect={this.appChange}>
                      {appOptions}
                    </Select>
                  )}
                </FormItem>
              </Col>

              <Col span={6}>

                <Spin spinning={this.state.templateLoading} delay={500}>
                  <FormItem>
                    {getFieldDecorator('template', {
                      initialValue: this.state.record ? this.state.record.template || null : null,rules: [
                        {required: true, message: 'Please select a template!'},
                      ],
                    })(
                      <Select placeholder="Message template" onSelect={this.templateChange}>
                        {templateOptions}
                      </Select>
                    )}
                  </FormItem>
                </Spin>
              </Col>
            </Row>


            <FormItem {...formItemLayout} label="Service Provider">
              {this.state.record.serviceName || ''}
            </FormItem>
            <FormItem {...formItemLayout} label="Channel Name">
              {this.state.record.channelName || ''}
            </FormItem>
            <FormItem {...formItemLayout} label="Business Scene">
              {this.state.record.bizFunctionDesc || ''}
            </FormItem>
            <FormItem {...formItemLayout} label="Template Content">
              {this.state.record.messageTemplateDesc || ''}
            </FormItem>
            <FormItem {...formItemLayout} label="Rule">
              {this.state.record.sendRuleName || ''}
            </FormItem>

            <FormItem  {...formItemLayoutWithOutLabel}>
              <Row>
                <Col span={12}>
                  <Button style={{marginLeft :6 ,float:'right'}} type="primary" htmlType="Confirm Cending" onClick={this.submit}
                        disabled={this.state.isBatchEntering ? this.state.fileList.length === 0 : false}>
                    Confirm Sending
                  </Button>
                  <Button style={{marginLeft :6,float:'right'}} type="primary"  onClick={this.resetForm}>
                    Reset Form
                  </Button>
                </Col>
              </Row>

            </FormItem>

          </Form>

        </Spin>
      </Card>
    )
    const formItemLayoutWithOutLabel = {
      wrapperCol: {
        xs: {span: 24, offset: 0},
        sm: {span: 22, offset: 2},
      },
    }
  }
}

SendOperationMsg = Form.create()(SendOperationMsg)
export default SendOperationMsg


